﻿using Kinlo.Entitys;
using Kinlo.MESDocking;
using NewLife;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using UIWindows.Enums;
using UIWindows.GlobalStatics;
using UIWindows.Models.Homes;
using UIWindows.Services.Context;
using UIWindows.Tools.Helper;
using UIWindows.ViewModels.Dialogs;
using XingLucifer.Devices;
using XingLucifer.IBase;
using XingLucifer.IBase.Enums;
using XingLucifer.IBase.Models.PLCInteraktion;

namespace UIWindows.Services.Handle
{
    [Attributes.TaskClass(TaskTypes.后称重)]
    public class AfterWeighing : ServierBase
    {
        private volatile int _weighingNG = 0, _total = 0, _lessLiquid = 0, _multiLiquid = 0, _LeakDetectionNG = 0;
        static object locker = new object();
        public AfterWeighing(DeviceConfigStatic deviceConfig, SystemConfigStatic systemConfig,
            UserConfigStatic userConfig, ParameterStatic parameterStatic, TemporaryStatic temporaryStatic, HomeStatic homeStatic, MesParameterStatic mesParameterStatic)
            : base(deviceConfig, systemConfig, userConfig, parameterStatic, temporaryStatic, homeStatic, mesParameterStatic)
        {
            _interaction = new ProduceOpenAddInterface(DialogLogHelper.MesLog, DialogLogHelper.MESDialog);
        }

        public override Task Handle(DataContext context)
        {
            if (!ClearSignal(context)) { return Task.CompletedTask; }
            var plc = _deviceConfig.DeviceList.FirstOrDefault(x => x.ServiceName == context.ServiceName && x.TaskType == TaskTypes.扫描信号).Communication as OmronCIP;
            try
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    _ = MaterialDesignThemes.Wpf.DialogHost.Show(new Views.Dialogs.WeighingDialog() { DataContext = new WeighingDialogViewModel(_parameterStatic) }, PopUpTypes.Global.ToString()).ConfigureAwait(false);
                });

                return base.Handle(context);


            }
            catch (Exception ex)
            {
                RunLog($"-[后称重]异常：{ex}");
                WriteCMD(1, plc, _systemConfig.IAddress.Alarm_AfterWeighing);
            }
            return base.Handle(context);
        }



        /// <summary>
        /// 样本标准差
        /// </summary>
        /// <param name="sixSigma"></param>
        /// <returns></returns>
        static double GetSpecificationStandardDeviation(List<double> valueList, ProcessCapabilityModel sixSigma) => Math.Sqrt(valueList.AsParallel().Select(item => Math.Pow(item - sixSigma.X, 2)).Sum() / (valueList.Count - 1));

        /// <summary>
        /// 表示制程特性的一致程度，值越大越集中
        /// </summary>
        /// <param name="sixSigma"></param>
        /// <returns></returns>
        static double GetCp(ProcessCapabilityModel sixSigma) => sixSigma.T / (6 * sixSigma.SpecificationStandardDeviation);

        /// <summary>
        /// Ca====表示制程特性中心位置的偏移程度
        /// </summary>
        /// <param name="sixSigma"></param>
        /// <returns></returns>
        static double GetCa(ProcessCapabilityModel sixSigma) => (sixSigma.X - sixSigma.U) / (sixSigma.T / 2);

        /// <summary>
        /// 考虑偏移及一致程度
        /// </summary>
        /// <param name="sixSigma"></param>
        /// <returns></returns>
        static double GetCpk(ProcessCapabilityModel sixSigma)
        {
            sixSigma.CpkU = Math.Abs(sixSigma.USL - sixSigma.X) / (3 * sixSigma.SpecificationStandardDeviation);
            sixSigma.CpkL = Math.Abs(sixSigma.X - sixSigma.LSL) / (3 * sixSigma.SpecificationStandardDeviation);
            return Math.Min(sixSigma.CpkU, sixSigma.CpkL);
        }
    }
}
